
<div class="full-screen">
    <header class="bg-red fixed" style="z-index: 200">
        <a id="scanQR" class="u-left"><img src="/wap_themes/xiaomi/images/icon/QR-icon.png" alt=""></a>
        <p class="u-title">商品分类</p>
        <a href="cart.html" class="u-right"><img src="/wap_themes/xiaomi/images/icon/cart-icon.png" alt=""></a>
    </header>

    <div class="pt-category" style="padding-top: 1rem;">

        <div class="content bg-white" >
            <div class="pt-gallery cat-gallery">
                <div class="tab J-tab">
                    <ul class="trigger-list static" style="top: .84rem;">
                        <li class="trigger ">
                            默认
                        </li>
                        <li class="trigger price-seq">
                            价格
                            <i class="arr down"></i>
                        </li>
                        <li class="trigger sales-seq act">
                            销量
                            <i class="arr down"></i>
                        </li>
                        <li class="filter-handle">
                            筛选
                            <div id="filter_container" style="display:none;">
                                <{include file='wap/gallery/screen.html'}>
                            </div>
                        </li>
                    </ul>
                </div>

            </div>


            <section class="m-main">
                <div class="g-left">
                    <ul class="m-item">

                        <li class="u-item all_cat" >
                            <a data-href="<{link app=b2c ctl=wap_gallery act=cat arg0=0}>" >
                                <div>
                                    <p>全部商品</p>
                                </div>
                            </a>
                        </li>
                        <{foreach from=$catlist item=item}>
                        <li class="u-item ">
                            <a data-href="<{link app=b2c ctl=wap_gallery act=cat arg0=$item.cat_id}>">
                                <div>
                                    <p><{$item.cat_name}></p>
                                </div>
                            </a>

                        </li>
                        <{/foreach}>


                    </ul>
                </div>

                <div class="g-right panel-list">

                </div>
            </section>

        </div>
    </div>
    <section class="m-input">
        <input type="hidden" value="" id="product_id">
        <input type="hidden" value="" id="old_num">
        <p class="u-title">输入订购数量</p>
        <p class="u-info">
            <span><span id="u-min"></span><span></span>件起订</span>
            <span>规格：<span id="u-size"></span></span>
            <span>单位：<span id="u-unit"></span></span>
        </p>
        <div>
            <input type="number" name="goods[num]" id="new_input" autofocus>
        </div>
        <div class="m-btn">
            <div class="u-btn u-cancle">取消</div>
            <div class="u-btn u-submit">确定</div>
        </div>
    </section>

    <section class="u-cover"></section>
</div>
<script src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
<script>

    window.addEventListener('pageshow', function(event) {
//        alert(event.persisted);
        if (event.persisted) location.reload();    //如果检测到页面是从“往返缓存”中读取的，刷新页面
    });

    //回到缓存滚动条位置
    if(sessionStorage.scrollTop!=0){
        console.log(sessionStorage.scrollTop)
        setTimeout(function () {
            document.body.scrollTop=sessionStorage.scrollTop;
            document.documentElement.scrollTop=sessionStorage.scrollTop;
        },400)

    }

    var type_id=0;


    sessionStorage.scrollTop_index=0;
    var container = document.body;
    var priceSeq = 'price desc';
    var salesSeq = 'buy_w_count desc';
    var url = '<{link app=b2c ctl=wap_gallery act=ajax_get_goods}>';
    var page = '1';
    var cat_id = '<{$screen.cat_id}>';

    var filter_dialog;
    var orderBy="<{$_orderBy}>";

    /*html5 history manage*/
    setTimeout(function(){
        window.history.replaceState({url: location.href, html: container.innerHTML}, null, location.href);
    }, 0);

    window.onpopstate = function(event){
        var data;
        if(event && event.state){
            data = event.state;
        }else{
            data = {html: container.innerHTML, url: location.href};
        }

        var scripts = '';
        var text = data.html.replace(/<script\b[^>]*>([\s\S]*?)<\/script>/gi, function(all, code){
            scripts += code + '\n';
            return '';
        });
        container.innerHTML = text;

        var script = document.createElement('script');
        script.text = scripts;
        document.body.appendChild(script);
        // document.head.removeChild(script);
    }


    //弹出输入框
    function showInput(a) {
        var $this=$(a).parents("li");
        var min_buy=$this.find(".u-min_buy").val();
        var good_standard=$this.find(".good_standard").val();
        var unit=$this.find(".u-unit").val();
        var num=parseInt($this.find(".u-num").text());
        var id=$this.find(".pt-h-link").attr("data-href");
        $("#product_id").val(id);
        $("#u-min").html(min_buy);
        $("#u-size").html(good_standard);
        $("#u-unit").html(unit);
        $(".m-input").show();
        $(".u-cover").css("display","block");
        $("#new_input,#old_num").val(num);

    }
    //改变分类ID
    function changeTypeId(id) {
        type_id=id;
    }
    //    显示分类及对应商品
    function showCat($a) {
        var $this=$a.parent(".u-item");
        $this.siblings(".u-item").removeClass("active");
        $this.addClass("active");
        var _href=$this.find("a").attr("data-href");
        $this.siblings(".u-item").find("ul,.u-down-icon").remove();

        if($this.parents("ul").length==3){
            $img=$("<img src='/wap_themes/xiaomi/images/icon/down.png'>");
            $img.css({
                "width":".2rem",
                "height":".2rem",
                "position":"absolute",
                "right":"0rem",
                "top":"50%",
                "marginTop":"-0.1rem",
                "transform": "rotate(-90deg)"
            });
            $this.siblings(".u-item").find("img").remove();
            $this.append($img);
        }
        if($this.find("ul").length>0){
            $a.find(".u-down-icon").animate({"transform":"rotate(180deg)"},200);
            setTimeout(function () {
                $a.find(".u-down-icon").remove();
            },200);
            $this.find("ul").remove();
            return;
        }
        else{
            $.post(_href,function (re) {
                try{
                    re=JSON.parse(re);
                    type_id=re[0].parent_id;
                    changeTypeId(type_id);
                    if(!re.length==0){
                        var $ul=$("<ul style='display: none'>");
                        $.each(re,function (index,value) {
                            var str='<li class="u-item u-child">';
                            var id=value.cat_id;
                            str+='<a onclick="showCat($(this))" data-href="<{link app=b2c ctl=wap_gallery act=cat arg0="'+id+'"}>">';
                            str+='<div><p>'+value.cat_name+'</p></div></a></li>';
                            $ul.append(str);
                        });
                        $this.append($ul);
                        $ul.show();
                        $a.children("div").append('<div><img src="/wap_themes/xiaomi/images/icon/down.png" class="u-down-icon" alt=""></div>');
                        $a.find(".u-down-icon").animate({"transform":"rotate(0deg)"},200);

                        if($this.parents("ul").length==1){
                            $this.children("ul").find("li").each(function(){
                                $(this).css("background","#f48451");
                            })
                        }
                        else if($this.parents("ul").length==2){
                            $this.children("ul").find("li").each(function(){
                                $(this).css("background","#fff");
                                $(this).find("a").css("color","#333");
                                $(this).addClass("last-child");
                            })
                        }
                        sessionStorage.catList=$(".g-left").html();
                    }
                }
                catch(e){}
            });
            if($this.hasClass("last-child")){
                var child_id=$this.find("a").attr("data-href");
                child_id=child_id.replace(/[^0-9]/ig,"");
                type_id=child_id;
                filterGoods($('.trigger-list .act'),null,1);
            }
        }
        //加载商品数据
        if($this.hasClass("all_cat")){
            type_id=0;
            filterGoods($('.trigger-list .act'),null,1);
            sessionStorage.catList=$(".g-left").html();
            return ;
        }
        else{
            type_id=$a.attr("data-href").replace(/[^0-9]/ig,"");
            filterGoods($('.trigger-list .act'),null,1);
        }
    }
    //    添加商品入购物车
    function addCart(a) {
        //判断登录跳转
        var e = $.fn.cookie('UNAME')?$.fn.cookie('UNAME'):'';
        console.log(e);
        if(!e){
            location.href="passport.html";
            return false;
        }
        var $this=$(a);
        var id=$this.parents(".pt-h-link").attr("data-href");
        var num=$this.siblings(".u-num").text();
        var add_href='<{link app=b2c ctl=wap_cart act=addCart arg0=goods arg1="'+id+'"}>?';
        var dec_href='<{link app=b2c ctl=wap_cart act=decCart arg0=goods arg1="'+id+'"}>?';
        console.log(add_href);
        if($this.hasClass("u-add")){
            $.post(add_href,function (re) {
                try{
                    re=JSON.parse(re);
                    if(re.success){
                        $this.parents(".u-product").find(".u-num").html(re.success);
                        add_frame($this);
                    }
                    if(re.error){
                        alert("库存不足，加入购物车失败");
                    }
                }
                catch (e){}
            })
        }
        else{
            $.post(dec_href,function (re) {
                try{
                    if(num==0||num<0){
                        return false;
                    }
                    re=JSON.parse(re);
                    if(re.success){
                        $this.parents(".u-product").find(".u-num").html(re.success);
                    }

                }
                catch (e){}
            })
        }
    }

    //    加入购物车动画
    function add_frame(a) {
        var $this=a.parents(".u-product").find("img");
        var old_top=$this.offset().top;
        var old_left=$this.offset().left;
        var _width=$this.width();
        var _height=$this.height();
        var $new_img=$this.clone();
        var scroll=document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
        if(old_top>scroll){
            old_top-=scroll;
        }
        $new_img.css({
            "position":"fixed",
            "width":_width,
            "height":_height,
            "left": old_left,
            "top": old_top,
            "z-index":"222",
            "border-radius":"2rem"
        });
        $("body").append($new_img);

        $new_img.animate({
            "width":".5rem",
            "height":".5rem",
            "top":".2rem",
            "left":"6.5rem"
        },550,"swing");

        setTimeout(function () {
            $new_img.remove();
        },575);

    }

    function filterGoods(t,e,status){
        var orderby = 'orderBy=',
            p = 'page=',
            sear = '',
            search = location.search;
        if(e&&$('.trigger-list .act').hasClass('price-seq')) orderby += priceSeq;
        else if(e&&$('.trigger-list .act').hasClass('sales-seq')) orderby += salesSeq;
        else if(t.hasClass('price-seq')){
            orderby += priceSeq;
        }
        else if(t.hasClass('sales-seq')){
            orderby += salesSeq;
        }
        if(e&&e.num){
            p += e.num;
            page = e.num;
        }
        //分两种情况，1是根据URL分类，2是根据点击改变URL而分类，3是缓存。传入status值执行点击的
        if(sessionStorage.params&&sessionStorage.params!=""&&!status){
            var params=sessionStorage.params;
            console.log("执行缓存")
        }
        else if(search&&!status){
            var params=search.substr(1);
            console.log("执行URL");
        }
        else{
            var params = ['showtype=list', p, encodeURI(orderby), sear, $('#J_filter form').serialize()].filter(function(d){
                return d;
            }).join('&');

            //add by hyz 2018.4.18
            //点击分页
            if (e) {
                // console.log(sessionStorage.params)
                arr=sessionStorage.params.split("=");
                type_id = arr['4'];
            }
            //add end
            
            params+="&cat_id="+type_id;
            console.log("执行点击");
        }
        $.post(url, params, function(re){
            var reg = location.search?location.search:location.href;
            window.history.pushState({url: location.href, html: container.innerHTML}, null, location.href.replace(reg, '?' + params));
            $(".g-right").empty();
            $(".g-right").append(re);
            sessionStorage.params=params;
        });
    }

    $('.J-tab .trigger').on('touchend',function(e){e.preventDefault();}).on('tap',function(){
        page = 1;
        $(this).addClass("act");
        $(this).siblings("li").removeClass("act");
        if( $(this).hasClass('sales-seq') ){
            $(this).siblings(".trigger").removeClass("act");
            $(this).addClass("act");
            salesSeq = salesSeq == 'buy_w_count desc' ? 'buy_w_count asc' : 'buy_w_count desc';
            if($(this).find('i')[0].className == 'arr down'){
                $(this).find('i')[0].className = 'arr top';
            }
            else{
                $(this).find('i')[0].className = 'arr down';
            }

        }
        else if ($(this).hasClass('price-seq')) {
            if(priceSeq == 'price desc'){
                $(this).siblings(".trigger").removeClass("act");
                $(this).addClass("act");
                priceSeq = 'price asc';
                $(this).find('i')[0].className = 'arr down';
            }else{
                priceSeq = 'price desc';
                $(this).find('i')[0].className = 'arr top';
            }
        }

        filterGoods($(this),null,1);
    });

    $('.filter-handle').on('click',function(){
        page = 1;
        filter_dialog = new Dialog('#filter_container',{'type':'confirm'});
    });

    $('.panel-list').on('click',function(e){
        var t = $(e.target);
        if(t.hasClass('flip')){
            t.num=parseInt($("option.flip[selected='selected']").attr("page")) ;
            if(t.hasClass('next'))t.num++;
            if(t.hasClass('prev'))t.num--;
            filterGoods($('.trigger-list .act'),t,1);
            $(window).scrollTop(0);
            return false;
        }
    }).on('change','select',function(){
        var t = $(this.options[this.selectedIndex]);
        if(t.hasClass('flip')){
            t.num = parseInt(t.attr('page'));
            filterGoods($('.trigger-list .act'),t,1);
            $(window).scrollTop(0);
        }
    });
    $('#J_filter').on('click',function(event){
        event.preventDefault();
        var _this = this,
            t = $(event.target),
            tag = t[0].tagName.toLowerCase(),
            table = t.parents('table');

        switch(tag){
            case 'dt':
                if( t.hasClass('handle') ){
                    t.removeClass('handle').next().addClass('hide');
                }else{
                    t.addClass('handle').next().removeClass('hide');
                    t.siblings('.handle').removeClass('handle').next().addClass('hide');
                }
                break;
            case 'td':
                if(t.hasClass('empty'))return;
                table.find('td').removeClass('handle');
                t.addClass('handle');
                table.parent().prev().find('span').html(t.html());
                var fid = t.attr('data-fid');
                if(fid&&fid.length){
                    fid = fid.split('-');
                    table.prev().attr({name:fid[0]+'[]',value:fid[1]});
                    table.parent().prev().find('span').addClass('act');
                }else{
                    var hide = table.prev();
                    if(/^cat_id/.test(hide.attr('name'))) {
                        hide.val(cat_id);
                    }
                    else {
                        hide.val('');
                    }
                    table.parent().prev().find('span').removeClass('act');
                }
                break;
            case 'span':
                if(t.hasClass('reset')){
                    $.each($(this).find('table'),function(){
                        $(this).find('td').eq(0).trigger('tap');
                    });
                }
                break;
            case 'input':
                filterGoods( $('.trigger-list .act'),t ,1);
                console.log(tag);
                filter_dialog.close();
                filter_dialog.close();
                break;
        }
    });





    //生成签名
    var appid="<{$SignPackage.appId}>";
    var timestamp="<{$SignPackage.timestamp}>";
    var nonceStr="<{$SignPackage.nonceStr}>";
    var signature="<{$SignPackage.signature}>";
    wx.config({
        // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
        debug: false,
        // 必填，公众号的唯一标识result.appId
        appId: appid,
        // 必填，生成签名的时间戳result.timestamp
        timestamp: timestamp,
        // 必填，生成签名的随机串
        nonceStr: nonceStr,
        // 必填，签名，见附录1
        signature: signature,
        // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
        jsApiList : [ 'checkJsApi', 'scanQRCode' ]
    });
    wx.error(function(re) {
//            alert("出错了：" + re.errMsg);
//            alert(signature);
    });
    wx.ready(function() {


        wx.checkJsApi({
            jsApiList : ['scanQRCode'],
            success : function(res) {

            }
        });
        //点击扫码按钮
        $("#scanQR").click(function(){
            wx.scanQRCode({
                needResult : 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
                scanType : [ "qrCode","barCode"], // 可以指定扫二维码还是一维码，默认二者都有
                success : function(res) {
                    var res = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
                    var pattern=/,/;
                    if(pattern.test(res)){
                        var s=res.split(",");
                        res=s[1];
                        $.post("<{link app=b2c ctl=wap_gallery act=getqrcode_data arg0='"+res+"'}>",function (re) {
                            $.ajax({
                                type: "GET",
                                cache: false,
                                url: re,
                                data: "",
                                success: function() {
                                    location.href=re;
                                },
                                error: function() {
                                    alert("此条码无效");
                                }
                            });
                        })
                    }
                }

            });
        });
    });

    $(".m-item>li:first-child").addClass("active");
    //session storage获取历史数据返回历史位置
    if(sessionStorage.catList!="empty" && sessionStorage.catList!= undefined){
        $(".g-left").html(sessionStorage.catList);
    }


    $(".m-item .u-item>a").bind("click",function () {
        showCat($(this));
    });
    //初始化页面数据
    filterGoods($(".trigger.sales-seq"));








    $(document).on("scroll",function () {
        sessionStorage.scrollTop=document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
    });


    //关闭输入框
    $(".u-cover,.u-cancle").on("click",function () {
        $(".m-input").hide();
        $(".u-cover").hide();
        $("#u-min").html("");
        $("#u-size").html("");
        $("#u-unit").html("");
    });
    //输入框提交
    $("#new_input").on("focus",function () {
        console.log("获取焦点");
    });
    $(".m-input .u-submit").on("click",function () {
        var min=parseInt($("#u-min").text());
        var input=parseInt($(this).parents(".m-input").find("input[type='number']").val()) ;
        var _id=parseInt($(this).parents(".m-input").find("#product_id").val());
        var old_num=parseInt($(this).parents(".m-input").find("#old_num").val());
        var $parents=$("div[data-href='"+_id+"']").parents("li");
        if(!input){
            alert("请输入购买数量");
        }
        else if(input%min!=0){
            alert("请输入以"+min+"为倍数的数量");
        }
        else{

            $.post("<{link app=b2c ctl=wap_cart act=entry arg0='goods'  arg1='"+_id+"' arg2='"+input+" ' }>",function (re) {
                re=JSON.parse(re);
                if(re.success){
                    alert("加入购物车成功");
                    $parents.find(".u-num").text(re.success);
                }
                else{
                    alert(re.error);
                }
                $(".m-input,.u-cover").hide();
            })
        }
    })






</script>